#!/bin/sh
# Start/stop/restart i8kmon.

I8KMON_PARAMS="--auto --daemon"

# Start i8kmon
i8kmon_start() {
  if [ -x /usr/bin/i8kmon -a -f /proc/i8k ]; then
    echo "Starting i8kmon daemon: /usr/bin/i8kmon $I8KMON_PARAMS &"
    /usr/bin/i8kmon $I8KMON_PARAMS &
  fi
}

# Stop i8kmon
i8kmon_stop() {
  echo "Stopping i8kmon daemon"
  pkill -f "tclsh /usr/bin/i8kmon $I8KMON_PARAMS"
}

# Check status
i8kmon_status() {
  pgrep -f "tclsh /usr/bin/i8kmon $I8KMON_PARAMS" > /dev/null
  local I8KMON_STATUS=$?
  if [ $I8KMON_STATUS -ne 0 ]; then
    return 1
  fi
}

# Restart i8kmon
i8kmon_restart() {
  $0 stop
  sleep 1
  $0 start
}

case "$1" in
'start')
  if ( ! i8kmon_status ); then
    i8kmon_start
  else
    echo "i8kmon is already running"
  fi
  ;;

'stop')
  if ( i8kmon_status ); then
    i8kmon_stop
  else
    echo "i8kmon is already stopped"
  fi
  ;;

'status')
  if ( i8kmon_status ); then
    echo "i8kmon is currently running"
  else
    echo "i8kmon is NOT running"
  fi
  ;;

'restart')
  i8kmon_restart
  ;;

*)
  echo "Usage: $0 start|stop|status|restart"
  ;;
esac
